package com.sgj.validator;

import com.sgj.utils.ValidatorUtil;
import org.thymeleaf.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 手机号码校验规则
 * @author 沈国纪
 * @date 2021/1/16 23:08
 */
public class IsMobileValidator implements ConstraintValidator<IsMobile, String> {

    private boolean required = false;

    @Override
    public void initialize(IsMobile constraintAnnotation) {
        // 是否必填
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (required) {
            // 如果必填,则去校验手机号码
            return ValidatorUtil.isMobile(value);
        } else {
            // 手机号码是否为空
            if (StringUtils.isEmpty(value)) {
                return true;
            } else {
                // 不为空则校验该手机号
                return ValidatorUtil.isMobile(value);
            }
        }
    }
}
